<?php

namespace App\Console\Commands\Shop;

use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Model\ShopRecordsModel;
use App\Kuafu\Shop\Model\ShopStaffRecordModel;
use App\Kuafu\User\Enum\RoleCodeEnum;
use App\Kuafu\User\Model\User;
use App\Kuafu\User\Model\UserIdCardDetailModel;
use App\Kuafu\User\Model\UserRoleMapping;
use Carbon\Carbon;
use Illuminate\Console\Command;

class InitShopAndShopStaffRecords extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'shop:init_shop_and_shop_staff_records {--shopIds=} {--init=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化门店和门店员工备案脚本';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        $shopIdArr = [];
        $shopIds   = (string)$this->option('shopIds');
        if (strlen($shopIds)) {
            $shopIdArr = explode(',', $shopIds);
        }

        $init = (int)$this->option('init');
        if ($init != 99 && !count($shopIdArr)) {
            $this->error('一次性脚本 请勿重复执行');
            return;
        }

        $existShopIds = ShopRecordsModel::query()
            ->whereIn('shopId', $shopIdArr)
            ->pluck('shopId')
            ->toArray();

        // 获取不存在的门店id
        $shopIdArr = array_diff($shopIdArr, $existShopIds);

        if (!count($shopIdArr)) {
            return;
        }

        // 获取含有身份证的用户
        $haveIdCardUserIds = UserIdCardDetailModel::query()
            ->pluck('userId')
            ->toArray();

        // 获得所有人的健康证时间
        $healthCardEndTime = User::query()
            ->where('healthCardEndDate', '!=', 0)
            ->pluck('healthCardEndDate', 'id')
            ->toArray();

        Shop::query()
            ->when(count($shopIdArr), function ($query) use ($shopIdArr) {
                $query->whereIn('id', $shopIdArr);
            })
            ->where('shopCode', '<', 9000)
            ->chunkById(100, function ($shops) use ($haveIdCardUserIds, $healthCardEndTime) {
                echo '.';
                $shopIds = [];
                foreach ($shops as $shop) {
                    $shopIds[] = $shop->id;
                }


                // 总在职人数
                $job = [];
                // 需到店人数
                $inShop = [];
                // 证件过期
                $expired = [];
                // 门店员工
                $shopStaff = [];
                // 门店所有员工
                $shopAllStaff = [];
                // 员工是否需要到店
                $staffInShop = [];
                // 离职员工
                $leaveStaff = [];
                // 员工离职入职时间
                $staffAboutPositionTime = [];
                // 员工创建人
                $staffCreatedUser = [];
                UserRoleMapping::query()
                    ->whereIn('shopId', $shopIds)
                    ->whereIn('type', [RoleCodeEnum::ROLE_POS_TYPE, RoleCodeEnum::ROLE_BUSINESS_TYPE])
                    ->withoutGlobalScope('isDel')
                    ->get()
                    ->map(function (UserRoleMapping $userRoleMapping) use (&$job, &$inShop, &$shopStaff, &$shopAllStaff, &$staffInShop, &$leaveStaff, &$staffAboutPositionTime, &$staffCreatedUser) {
                        $shopAllStaff[$userRoleMapping->shopId][] = $userRoleMapping->userId;
                        $staffCreatedUser[$userRoleMapping->shopId . '-' . $userRoleMapping->userId] = $userRoleMapping->createdByUid;
                        $staffAboutPositionTime[$userRoleMapping->shopId . '-' . $userRoleMapping->userId] = [
                            'entryTime' => $userRoleMapping->entryTime,
                            'leaveTime' => $userRoleMapping->leaveTime,
                        ];
                        if ($userRoleMapping->isDeleted == 1) {
                            $leaveStaff[$userRoleMapping->shopId . '-' . $userRoleMapping->userId] = true;
                        } else {
                            $staffInShop[$userRoleMapping->shopId . '-' . $userRoleMapping->userId] = $userRoleMapping->inShop;
                            if (!isset($job[$userRoleMapping->shopId])) {
                                $job[$userRoleMapping->shopId] = [$userRoleMapping->userId];
                            } else {
                                $job[$userRoleMapping->shopId][] = $userRoleMapping->userId;
                            }
                            if ($userRoleMapping->inShop == 0) {
                                if (!isset($inShop[$userRoleMapping->shopId])) {
                                    $inShop[$userRoleMapping->shopId] = [$userRoleMapping->userId];
                                } else {
                                    $inShop[$userRoleMapping->shopId][] = $userRoleMapping->userId;
                                }
                                $shopStaff[$userRoleMapping->shopId][] = $userRoleMapping->userId;
                            }
                        }
                    });
                // 获取证件过期的用户
                foreach ($shopStaff as $shopId => $staff) {
                    $expired[$shopId] = User::query()
                        ->whereIn('id', $staff)
                        ->where('healthCardEndDate', '<', time())
                        ->count();
                }

                // 门店备案
                $shopRecordInsertData = [];
                foreach ($shops as $shop) {
                    $shopRecordInsertData[] = [
                        'shopId'            => $shop->id,
                        'shopCode'          => $shop->shopCode,
                        'staffCount'        => count(array_unique($job[$shop->id] ?? [])),
                        'inShopStaffCount'  => count(array_unique($inShop[$shop->id] ?? [])),
                        'cardAbnormalCount' => $expired[$shop->id] ?? 0,
                        'pendingCount'      => count(array_unique($inShop[$shop->id] ?? [])) - ($expired[$shop->id] ?? 0),
                    ];
                }

                // 员工备案
                $shopStaffRecordInsertData = [];
                foreach ($shops as $shop) {
                    foreach ((isset($shopAllStaff[$shop->id]) ? array_unique($shopAllStaff[$shop->id]) : []) as $userId) {
                        // 职位状态
                        $positionStatus = ShopStaffRecordModel::POSITION_STATUS_ON;

                        // 审核状态
                        $auditStatus = ShopStaffRecordModel::AUDIT_STATUS_EXPIRED_OR_LACK;
                        if (isset($staffInShop[$shop->id . '-' . $userId]) && $staffInShop[$shop->id . '-' . $userId] == 0) {
                            $auditStatus = ShopStaffRecordModel::AUDIT_STATUS_WAIT_AUDIT;
                        }

                        // 处理健康证状态
                        $healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_UPLOADED;
                        if (!isset($healthCardEndTime[$userId])) {
                            $healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_LACK;
                            $auditStatus      = ShopStaffRecordModel::AUDIT_STATUS_EXPIRED_OR_LACK;
                        } else {
                            if ($healthCardEndTime[$userId] <= time()) {
                                $healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_EXPIRED;
                                $auditStatus      = ShopStaffRecordModel::AUDIT_STATUS_EXPIRED_OR_LACK;
                            }

                            if ($healthCardEndTime[$userId] > time() && $healthCardEndTime[$userId] < Carbon::now()->addDays(30)->timestamp) {
                                $healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_ABOUT_TO_EXPIRE;
                            }

                        }

                        // 身份证状态
                        if (in_array($userId, $haveIdCardUserIds)) {
                            $idCardStatus = ShopStaffRecordModel::ID_CARD_STATUS_UPLOADED;
                        } else {
                            $idCardStatus = ShopStaffRecordModel::ID_CARD_STATUS_LACK;
                        }

                        // 不到店
                        if (isset($staffInShop[$shop->id . '-' . $userId]) && $staffInShop[$shop->id . '-' . $userId] == 1) {
                            $auditStatus      = ShopStaffRecordModel::AUDIT_STATUS_NOT_IN_SHOP;
                            //$healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_NULL;
                            //$idCardStatus     = ShopStaffRecordModel::ID_CARD_STATUS_DEFAULT;
                        }

                        if (isset($leaveStaff[$shop->id . '-' . $userId])) {
                            $auditStatus      = ShopStaffRecordModel::AUDIT_STATUS_LEAVE;
                            $positionStatus   = ShopStaffRecordModel::POSITION_STATUS_OFF;
                            //$healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_NULL;
                            //$idCardStatus     = ShopStaffRecordModel::ID_CARD_STATUS_DEFAULT;
                        }

                        $shopStaffRecordInsertData[] = [
                            'shopId'           => $shop->id,
                            'shopCode'         => $shop->shopCode,
                            'userId'           => $userId,
                            'inShop'           => $staffInShop[$shop->id . '-' . $userId] ?? 0,
                            'entryTime'        => $staffAboutPositionTime[$shop->id . '-' . $userId]['entryTime'] ?? 0,
                            'leaveTime'        => $staffAboutPositionTime[$shop->id . '-' . $userId]['leaveTime'] ?? 0,
                            'auditStatus'      => $auditStatus,
                            'healthCardStatus' => $healthCardStatus,
                            'idCardStatus'     => $idCardStatus,
                            'positionStatus'   => $positionStatus,
                            'createdByUid'     => $staffCreatedUser[$shop->id . '-' . $userId]['leaveTime'] ?? 0,
                        ];
                    }
                }


                // 入库
                if (count($shopRecordInsertData)) {
                    ShopRecordsModel::query()->insert($shopRecordInsertData);
                }
                if (count($shopStaffRecordInsertData)) {
                    ShopStaffRecordModel::query()->insert($shopStaffRecordInsertData);
                }

            });


    }
}
